<template>
  <div class="r-uploader-wrapper">
    <div class="r-uploader-imagelist">
      <div
        class="r-uploader-container"
        @click="(event) => handleFileUploader(event, 'click')"
      >
        <slot name="uploader-area"></slot>
        <input
          type="file"
          class="r-file__invisible"
          ref="file"
          @change="(event) => handleFileUploader(event, 'change')"
        />
      </div>
    </div>
    <div>
      <slot name="tip"></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "w-uploader",

  data() {
    return {
      sourceFile: [],
    };
  },
  props: {
    accept: {
      type: String,
    },
    size: {
      type: Number,
    },
    onSuccess: {
      type: Function,
    },
    onError: {
      type: Function,
    },
  },
  mounted() {},

  methods: {
    handleFileUploader(event, type) {
      let handler = {
        click: () => {
          this.$refs.file.click();
        },
        change: () => {
          this.sourceFile = event.target.files;
        },
      };
      handler[type](event);
    },
  },
  watch: {
    sourceFile(value) {
      let files = Array.from(value);
      if (files.length <= 0) return;
      let { size, accept } = this;
      if (files.some((file) => file.size > size)) {
       return this.onError("文件超过大小");
      }
      if (files.some((file) => !~accept.indexOf(file.type))) {
       return this.onError("只接受" + this.accept + "类型文件");
      }
    },
  },
};
</script>

<style scoped>
@import "./uploader.css";
</style>